<?php
namespace api\controllers;

use Yii;
use yii\web\Controller;
use EasyWeChat\Foundation\Application;
use api\helpers\JWT;

class WechatController extends Controller
{

    public function behaviors()
    {
        return [
            'corsFilter' => [
                'class' => \yii\filters\Cors::className(),
                'cors' => [
                    'Origin' => ['*'],
                    'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
                    'Access-Control-Request-Headers' => ['*'],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $session = Yii::$app->session;
        $session['cid'] = '7';
        //if ($cid = Yii::$app->request->get('cid', null)) {
        //    $session['cid'] = $cid ? $cid : '7';
        //}
        $app = new Application(Yii::$app->params['wechat_options']);
        $oauth = $app->oauth;
        return $oauth->redirect()->send();
    }

    public function actionOauthCallback()
    {
        $session = Yii::$app->session;
        $app = new Application(Yii::$app->params['wechat_options']);
        $oauth = $app->oauth;
        $user = $oauth->user();
        $data['cid'] = '7';
        //$data['cid'] = $session['cid'] ? $session['cid'] : '7';
        $data['access_token'] = JWT::getToken($user);
        Yii::$app->response->redirect('http://tpapp.apiary.com.cn/#/?' . http_build_query($data))->send();
        //Yii::$app->response->redirect('http://tpapp.apiary.com.cn:8080/#/?' . http_build_query($data))->send();
        //Yii::$app->response->redirect(Yii::$app->request->headers['origin'] . http_build_query($data))->send();
        //Yii::$app->response->redirect('http://localhost:8080/#/?' . http_build_query($data))->send();

    }

    public function actionTest()
    {
        $session = Yii::$app->session;
        if ($cid = Yii::$app->request->get('cid')) {
            $session['cid'] = $cid;
        }
    }

    public function actionSign($url) 
    {
        $app = new Application(Yii::$app->params['wechat_options']);
        $js = $app->js;
        $js->setUrl($url);
        return $js->config([
            'onMenuShareAppMessage',
            'onMenuShareTimeline'
        ], false);
    }

}
